package com.jvmoutofmemory.octopus.util;

import com.jvmoutofmemory.octopus.model.FileModel;
import com.jvmoutofmemory.octopus.ui.MainOctopusFrame;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class PrintUtil {

    public static void print(File file) throws IOException {
        Desktop.getDesktop().print(file);
    }

    public static void printAll(MainOctopusFrame mainOctopusFrame, List<FileModel> fileModels, Integer interval) {
        for (FileModel model : fileModels) {
            if (model.getStatusCode() == FileModel.status_printed
                    && JOptionPane.showConfirmDialog(mainOctopusFrame, "选择的文件中存在已打印的文件,  确定重新打印吗?",
                    "重复打印确认", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) {
                return;
            }
        }

        for (FileModel model : fileModels) {
            if (model == null || model.getFile() == null) {
                continue;
            }

            try {
                PrintUtil.print(model.getFile());
                model.setStatusCode(FileModel.status_printed);
                model.setStatus("打印完成");
                if (fileModels.size() > 1 && interval != null && interval > 0) {
                    TimeUnit.SECONDS.sleep(interval);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(mainOctopusFrame,
                        "打印文件 " + model.getName() + "失败! ",
                        "打印失败", JOptionPane.ERROR_MESSAGE);
            }
        }

        mainOctopusFrame.renderTableData();
    }

}
